<template>
  <el-dialog
    :visible.sync="isShow"
    width="600px"
    :show-close="false"
    class="register"
  >
    <div class="title" slot="title">用户注册</div>
    <el-form
      :model="form"
      class="form"
      :rules="rules"
      ref="form"
      label-width="70px"
      label-position="left"
    >
      <!-- 上传头像 -->
      <el-form-item label="头像" prop="avatar">
        <el-upload
          class="avatar-uploader"
          name="image"
          :action="baseURL + '/uploads'"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="imageUrl" :src="baseURL + '/' + imageUrl" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>

      <el-form-item prop="username" label="昵称">
        <el-input v-model="form.username"> </el-input>
      </el-form-item>
      <el-form-item prop="email" label="邮箱">
        <el-input v-model="form.email"> </el-input>
      </el-form-item>
      <el-form-item prop="phone" label="手机">
        <el-input v-model="form.phone"> </el-input>
      </el-form-item>
      <el-form-item prop="password" label="密码">
        <el-input v-model="form.password" show-password> </el-input>
      </el-form-item>
      <el-form-item prop="code" label="图形码">
        <el-row>
          <el-col :span="15">
            <el-input v-model="form.code"> </el-input>
          </el-col>
          <el-col :span="8" :offset="1">
            <img :src="baseURL + codeUrl" class="login-avatar" alt="" @click="imgbtn" />
          </el-col>
        </el-row>
      </el-form-item>
      <!-- 栅栏 -->
      <el-form-item prop="rcode" label="验证码">
        <el-row>
          <el-col :span="15">
            <el-input v-model="form.rcode"> </el-input>
          </el-col>
          <el-col :span="8" :offset="1">
            <el-button @click="getCode" :disabled="totaltime!=5">获取用户验证码<span v-if="totaltime!=5">({{totaltime}})</span></el-button> 
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button @click="isShow = false">取消</el-button>
      <el-button type="primary" @click="submit">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {getPhoneCode,goRegister} from '@/api/register.js'
export default {
  //侦听事件
  watch:{
    isShow(newVal){

      if(newVal == false){
        this.$refs.form.resetFields()
        this.imageUrl=''
    }

    }
  },
  data() {
    return {
      totaltime:5,
      baseURL: process.env.VUE_APP_URL,
      imageUrl: "",
      isShow: false,
      codeUrl: "/captcha?type=sendsms",
      form: {
        username: "",
        phone: "",
        email: "",
        avatar: "",
        password: "",
        code:'',
        rcode: "",
      },
      rules: {
        avatar: [
          { required: true, message: "请选择一张图片", trigger: "change" },
        ],
        username: [{ required: true, message: "请输入昵称", trigger: "change" }],
        email: [
          { required: true, message: "请输入邮箱", trigger: "change" },
          {
            validator: (rule, value, callback) => {
              let reg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
              if (reg.test(value)) {
                callback();
              } else {
                callback(new Error("请正确输入邮箱"));
              }
            },
            trigger: "change",
          },
        ],
        phone: [
          { required: true, message: "请输入手机号", trigger: "change" },
          {
            validator: (rule, value, callback) => {
              let reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/;
              if (reg.test(value)) {
                callback();
              } else {
                callback(new Error("请正确输入手机号"));
              }
            },
            trigger: "change",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "change" },
          { min: 6, max: 12, message: "请输入6-12位的密码", trigger: "change" },
        ],
        code: [
          { required: true, message: "请输入图形码", trigger: "change" },
        ],
        rcode: [
          { required: true, message: "请输入验证码", trigger: "change" },
          { min: 4, max: 4, message: "请输入正确的验证码", trigger: "change" },
        ],
      },
    };
  },
  methods: {
    handleAvatarSuccess(res) {
      console.log(res);
      //   this.imageUrl = URL.createObjectURL(file.raw);//file文件对象转换成了blob本地地址
      this.imageUrl = res.data.file_path;
      this.form.avatar = res.data.file_path;
      this.$refs.form.validateField(["avatar"]);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    //注册事件
    submit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          goRegister(this.form)
          .then(res=>{
            console.log(res);
            this.isShow == true
            this.$message.success("注册成功");
            this.isShow =false
          }).catch(err=>{
            console.log(err);
          })
        } else {
          this.$message.error("注册失败");
          return false;
        }
      });
    },
    //修改验证码
    imgbtn(){
    this.codeUrl="/captcha?type=sendsms&ssafs=" + Date.now()
    },
    //获取手机号与图形码进行验证
    getCode(){
      let num=0;
      this.$refs.form.validateField(['phone','code'],err=>{
        console.log(err);
        if(err==""){
          num++
        }
      })
      if(num==2){
        this.totaltime--
        let _id = setInterval(()=>{
          this.totaltime--
          if(this.totaltime==0){
            this.totaltime=5
            clearInterval(_id)
          }
        },1000)
        getPhoneCode({
            phone:this.form.phone,
            code:this.form.code
          }).then(res=>{
          console.log(res);
          if(res.data.code == 200){
            this.$message.success(res.data.data.captcha+'')
          }else{
            this.$message.error(res.data.message)
          }
        })

      }else{
        this.$message.error('请输入手机号与验证码')
      }
    }
  },
  created() {
    this.imgbtn()
  },
};
</script>

<style lang="less">
.register {
  .title {
    width: 600px;
    height: 53px;
    text-align: center;
    line-height: 53px;
    background: linear-gradient(to right, #01c4fa, #1394fa);
  }
  .el-dialog__header {
    padding: 0;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 178px;
    height: 178px;
    // display: flex;
    // justify-content: center;
    display: block;
    margin: 0 auto;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}
</style>
